package com.exam.api.config.validation.validator;

import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;

import java.util.Arrays;
import java.util.stream.Collectors;

public class InEnumValidator implements ConstraintValidator<InEnum, String> {

    private Class<?> enumClass;

    @Override
    public void initialize(InEnum inDictionary) {
        this.enumClass = inDictionary.value();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (StrUtil.isEmpty(value)){
            return true;
        }
        HibernateConstraintValidatorContext context = constraintValidatorContext.unwrap(HibernateConstraintValidatorContext.class);
        if (enumClass.isEnum()) {
            Object[] enumConstants = enumClass.getEnumConstants();
            boolean anyMatch = Arrays.stream(enumConstants).anyMatch(constant -> ((Enum<?>) constant).name().equals(value));
            if (!anyMatch) {
                String collected = Arrays.stream(enumConstants).map(constant -> ((Enum<?>) constant).name()).collect(Collectors.joining(StrPool.COMMA));
                context.addMessageParameter("dictionary", value);
                context.addMessageParameter("collected", collected);
                context.buildConstraintViolationWithTemplate("字典不存在 “{dictionary}” 仅支持 “{collected}”").addConstraintViolation();
                return false;
            }
            return true;
        }
        throw new IllegalArgumentException("必需为EnumClass");
    }
}
